// Copyright (c) 2019 Presto Labs Pte. Ltd.
// Author: xguo

#pragma once

#include <string>

#include <glog/logging.h>
#include <google/protobuf/util/json_util.h>

inline std::string ProtoToJsonString(const google::protobuf::Message& message) {
  using google::protobuf::util::JsonPrintOptions;
  using google::protobuf::util::MessageToJsonString;

  JsonPrintOptions options;
  options.add_whitespace = true;
  options.always_print_primitive_fields = false;
  options.preserve_proto_field_names = true;

  std::string json_string;
  MessageToJsonString(message, &json_string, options);
  return json_string;
}

inline bool JsonStringToProto(const std::string& json_string, google::protobuf::Message* proto) {
  using google::protobuf::util::JsonParseOptions;
  using google::protobuf::util::JsonStringToMessage;
  JsonParseOptions options;
  options.ignore_unknown_fields = true;
  auto status = JsonStringToMessage(json_string, proto, options);
  if (!status.ok()) {
    LOG(ERROR) << status;
  }
  return status.ok();
}
